package netWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Homework02SenderB {
    public static void main(String[] args) throws UnknownHostException {
        try(DatagramSocket socket = new DatagramSocket();
            Scanner scanner = new Scanner(System.in)) {
           while (true){
               System.out.println("->");
               String request = scanner.next();
               //发送请求
               socket.send(new DatagramPacket(request.getBytes(),0,
                       request.getBytes().length, InetAddress.getByName("127.0.0.1"),9999));
               DatagramPacket responsePacket = new DatagramPacket(new byte[4096],0,4096);
               socket.receive(responsePacket);
               String response = new String(responsePacket.getData(),0,responsePacket.getLength());
               if(response.equals("0")){
                   System.out.println("客户端结束....");
                   break;
               }
               System.out.printf("[%s %d] req : %s resp: %s\n",responsePacket.getAddress().getHostAddress(),
                       responsePacket.getPort(),request,response);
           }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
